package com.sleep.ruledemo.api;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.IdUtil;
import com.sleep.ruledemo.domian.FileResult;
import com.sleep.ruledemo.domian.R;
import com.sleep.ruledemo.util.OSSUtils;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

/**
 * @author GuoAo
 * @className FileController
 * @date 2025/3/15
 * @description TODO
 */
@RestController
@RequestMapping("/file")
public class FileController {

    @PostMapping("/upload")
    public R upload(@RequestParam("file") MultipartFile file) throws IOException {
        InputStream inputStream = file.getInputStream();
        long snowflakeNextId = IdUtil.getSnowflakeNextId();
        LocalDate now = LocalDate.now();
        DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy.MM.dd");
        String fileName = format.format(now) + "\\"+ snowflakeNextId;
        String suffix = "jpg";
        fileName = fileName + "." + suffix;
        String filePath = "D:\\workspace\\file\\image\\"+fileName;
        FileUtil.writeFromStream(inputStream, new File(filePath));
        return R.ok(new FileResult().setFileName(fileName).setFilePath(filePath));
    }

    @PostMapping("/minio")
    public R uploadMinio(@RequestParam("file") MultipartFile file) throws IOException {
        String demo = OSSUtils.upload(file, "demo", "image");
        String url = OSSUtils.getURL("demo", demo);
        return R.ok(url);
    }
}
